<?php

namespace App\Http\Controllers\Home;

use App\Helpers\Helpers;
use App\Model\Activity;
use App\Model\ActivityClick;
use App\Model\ActivityHelp;
use App\Model\ActivityOrders;
use App\Model\WeChatFromId;
use App\Model\WeChatNotify;
use App\Model\WineProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class ActivityController extends BaseController
{
    //活动详细
    public function detail($id)
    {
        if ($formid = \request('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        //保存点击量
        $m = new ActivityClick();
        $m->activity_id = $id;
        $m->user_id = $this->loginUserId();
        $m->save();

        $item = Activity::find($id);

        if ($item) {

            if ($item->end_time < date('Y-m-d H:i:s')){
                $item->state = "finished";
                $item->save();
                ActivityOrders::changeState($item);
            }


            $products = WineProduct::whereRaw('`id` in (select product_id from activity_products where activity_id=?)',[$item->id])->get();

            $productItems = [];

            foreach ($products as $product){
                $productItems[] = [
                    'id'=>$product->id,
                    'name'=>$product->name,
                    'chateauName' => $product->chateauName,
                    'chname'=>$product->chname,
                    'covers'=>$product->covers,
                ];
            }

            $item->products = $productItems;

            $item->lecturer = DB::table('t_user')->where('id','=',[$item->lecturer_id])
                ->select('id','name')->first();


            $userItem =  ActivityOrders::where('user_id','=',$this->loginUserId())
                ->where('activity_id','=',$item->id)
                ->first();

            if ($userItem) {
                $userItem->user = DB::table('t_user')->select('id','name','avatar')->find($userItem->user_id);
                $userItem->helps  = $userItem->helps()->select('activity_helps.id','activity_helps.user_id','activity_helps.name',
                    'activity_helps.avatar','activity_helps.isNewUser')
                    ->get();
            }

            $item->userActivity = $userItem;

            $item->nextItem = $this->getNext($item);

        }

        //更新点击量
        DB::select('update activities set click_count=click_count+1 where id=?',[$id]);

        return $this->success($item);
    }

    //我的活动列表
    public function index(Request $request)
    {
        $query = ActivityOrders::where('user_id','=',$this->loginUserId());

        $type = $request->input('type',false);
        $typeAttr = ['uncomplete'=>0,'complete'=>1];

        if ($type !== false && isset($typeAttr[$type])) {
            $query = $query->where('apply_state','=',$typeAttr[$type]);
        }

        $items = $query->get()->map(function ($item){
            return $item->append('dead_line')->setHidden(['activity','openid','feedback']);
        });

        return $this->success($items);
    }

    //我的活动详细
    public function show($id)
    {
        if ($formid = \request('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $item = $this->getUserActivityItem($id);

        //$item = ActivityOrders::find($id);
        if ($item){
            $item->nextItem = $this->getNext($item->activity);
            return $this->success($item);
        }
        return $this->notFond();
    }

    //报名
    public function store(Request $request)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $rules = [
            'activity_id' => [
                'required',
                Rule::exists('activities','id')->whereNull('deleted_at')->where('state','publish')
            ],
            'name' => 'required|max:20',
            'mobile' => [
                'required',
                'regex:/^1[345789]{1}\d{9}$/'
            ],
            'location' => 'required|min:6|max:50'
        ];

        $message = [
            'name.required' => '姓名必填',
            'name.max' => '姓名超过有效长度',
            'mobile.required' => '手机号码必填',
            'mobile.max' => '请填写有效的手机号码',
            'location.required' => '地址必填',
            'location.min' => '请填写有效的地址信息',
            'activity_id.exists' => '活动不存在或已结束'
        ];

        if(!$this->requestValidate($request->all(),$rules,$message)){
            return $this->failed($this->error);
        }

        $ac = Activity::find($request->input('activity_id'));

        if ($ac->toll == 1) {
            $parent_order_id = $request->input('parent_order_id',false);
            $pac = ActivityOrders::where('parent_id','=',0)->find($parent_order_id);
            if (!$pac){
                return $this->failed('无效');
            }
        }
        if (strtotime($ac->deadline .' 23:59:59') < time()) {
            return $this->failed('报名已截至');
        }

        if ($ac->start_time > date('Y-m-d H:i:s')){
            return $this->failed('活动暂未开始');
        }


        if ($ac->end_time < date('Y-m-d H:i:s') && $ac->state != "publish"){
            return $this->failed('活动已结束');
        }

        //已报名数量
        $signPassCount = Activity::getFreeSignPassCount($ac->id);
        $ac->sign_count = $signPassCount;
        $ac->save();

        if($signPassCount  >= $ac->participate_limit){
            $ac->state = "finished";
            $ac->save();
            return $this->failed('名额已满员');
        }

        $data = $request->only('activity_id','name','mobile','location');

        $m = ActivityOrders::where('activity_id','=',$data['activity_id'])
            ->where('user_id','=',$this->loginUserId())->first();

        if ($m) return $this->failed('您已经参加此次活动，请勿重复报名！');

        $user = $this->loginUser();

        $m = new ActivityOrders();
        $m->fill($data);
        $m->user_id = $user->id;
        $m->openid = $user->weixinId;
        $m->out_trade_no = Helpers::createSerial('activity_orders','out_trade_no',date('Ymd'));
        $m->activity_name = $ac->name;
        if ($ac->covers) $m->activity_cover = $ac->covers[0];
        $m->apply_rule = $ac->share_rule;
        $m->is_pay = 0;
        $m->send_pass = 0;
        $m->state = 1;

        if($ac->toll == 1){
            $m->toll = 1;
            $m->apply_state = 0;
            $m->parent_order_id = $pac->id;
        }else{
            $m->toll = 0;
            $m->apply_state = $ac->need_share==0?1:0;
        }

        $m->save();

        DB::table('t_user')->where('id','=',$m->user_id)->update([
            'activity_count' => DB::table('activity_orders')->where('user_id','=',$m->user_id)->count(),
        ]);

        return $this->success($this->getUserActivityItem($m->id));

    }

    //免费活动助力
    public function freeHelp(Request $request,$id)
    {
        $user = $this->loginUser();

        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$user->weixinId);
        }

        $newUser = $request->input('newUser',false);

        $newUser = $newUser=="true"?true:($user->login_count==1?true:false);

        $activityOrder =  ActivityOrders::where('apply_state','=',0)
            ->where('state','=',1)
            ->where('user_id','<>',$user->id)
            ->find($id);

        if (!$activityOrder) return $this->failed('助力无效或已完成');

        if ($activityOrder->activity->end_time < date('Y-m-d H:i:s')){
            $activityOrder->activity->state = "finished";
            $activityOrder->activity->save();
            ActivityOrders::changeState($activityOrder->activity);
        }

        if ($activityOrder->state == 6) {
            return $this->failed('活动已结束');
        }

        $c = ActivityHelp::where('activity_order_id','=',$id)->where('user_id','=',$user->id)
            ->whereNull('deleted_at')->count();

        if ($c>0) return $this->failed('您已经助力了');

        $m = new ActivityHelp();
        $m->activity_order_id = $id;
        $m->activity_user_id = $activityOrder->user->id;
        $m->activity_user_name = $activityOrder->user->name;
        $m->activity_user_avatar = $activityOrder->user->avatar;
        $m->user_id = $user->id;
        $m->name = $user->name;
        $m->avatar = $user->avatar;
        $m->isNewUser = $newUser?1:0;
        $m->save();

        $activityOrder->changeApplyStateByHelp();

        return $this->message('ok');
    }

    //保存form_id用于发送消息
    public function saveFormId(Request $request)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
            return $this->message('ok');
        }

        return $this->failed('failed');
    }

    //确认收货
    public function complete(Request $request,$id)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $user = $this->loginUser();
        $order = ActivityOrders::where('user_id','=',$user->id)->find($id);

        if (!$order) return $this->notFond();

        if ($order->state == 4) {
            $order->state = 5;
            $order->receipt_time = date('Y-m-d H:i:s');
            $order->feedback_deadline = date('Y-m-d H:i:s',time()+14*24*3600);
            $order->save();


            //发送确认收货成功模板消息
            $m = new WeChatNotify();
            $m->applyFeedback($order);

            return $this->message('ok');
        }
        return $this->failed('fail');
    }

    private function getUserActivityItem($id)
    {
        $item = ActivityOrders::find($id);
        if ($item){

            if ($item->activity->end_time < date('Y-m-d H:i:s')){
                $item->activity->state = "finished";
                $item->activity->save();
                ActivityOrders::changeState($item->activity);
            }

            $products = WineProduct::whereRaw('`id` in (select product_id from activity_products where activity_id=?)',[$item->activity_id])->get();

            $productItems = [];

            foreach ($products as $product){
                $productItems[] = [
                    'id'=>$product->id,
                    'name'=>$product->name,
                    'chateauName' => $product->chateauName,
                    'chname'=>$product->chname,
                    'covers'=>$product->covers,
                ];
            }

            $item->products = $productItems;
            $item->user = DB::table('t_user')->select('id','name','avatar')->find($item->user_id);
            $item->helps  = $item->helps()->select('activity_helps.id','activity_helps.user_id','activity_helps.name',
                'activity_helps.avatar','activity_helps.isNewUser')
                ->get();

            $item->participate_limit = $item->activity->participate_limit;
            $item->activity_sign_count = $item->activity->sign_count;


        }

        return $item;
    }

    private function getNext($cur)
    {
//        $item = Activity::where('state','=','publish')->where('start_time','>=',$cur->start_time)
//            ->where('id','<>',$cur->id)
//            ->where('end_time','>',date('Y-m-d H:i:s'))
//            ->where('deadline','<=',date('Y-m-d'))
//            ->orderBy('start_time','asc')
//            ->orderBy('id','asc')
//            ->first();

        $item = $cur->nextActivity;

        if ($item){
            $products = WineProduct::whereRaw('`id` in (select product_id from activity_products where activity_id=?)',[$item->id])->get();

            $productItems = [];

            foreach ($products as $product){
                $productItems[] = [
                    'id'=>$product->id,
                    'name'=>$product->name,
                    'chateauName' => $product->chateauName,
                    'chname'=>$product->chname,
                    'covers'=>$product->covers,
                ];
            }

            $item->products = $productItems;

            $item->poster = "http://cdn.letsdrink.com.cn/letsDrink/image/20180730/hFHPOSXRi7LK9PoqnpaQoZYQRHDGe6njNqnh1y3GN3sjwQeziyytPvPnmmhDa0ro.png";
        }
        return $item;
    }
}
